package com.jly.edu.security.jwt;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jly.edu.entity.SysUser;
import com.jly.edu.security.service.UserDetailsServiceImpl;
import com.jly.edu.service.SysUserService;
import com.jly.edu.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.TreeSet;

@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailsServiceImpl userDetailService;

    @Autowired
    private SysUserService sysUserService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取jwt
        log.info("jwt 校验 filter");
        String jwt = request.getHeader(jwtUtils.getHeader());
        if (StrUtil.isBlankOrUndefined(jwt)) {
            chain.doFilter(request, response);
            return;
        }
        Claims claimByToken = jwtUtils.getClaimByToken(jwt);
        if (claimByToken == null) {
            throw new JwtException("token 异常");
        }

        if (jwtUtils.isTokenExpired(claimByToken)) {
            throw new JwtException("token已过期");
        }
        /**
         * 获取到用户名之后我们直接把封装成UsernamePasswordAuthenticationToken，
         * 之后交给SecurityContextHolder参数传递authentication对象，
         * 这样后续security就能获取到当前登录的用户信息了，也就完成了用户认证
         */
        String username = claimByToken.getSubject();
        log.info("用户-{}，正在登陆！", username);
        //获取用户权限
        SysUser sysUser = sysUserService.getByUsername(username);
        List<GrantedAuthority> authorities = userDetailService.getUserAuthority(sysUser.getId());
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, null, authorities);
        SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
        chain.doFilter(request, response);

    }
}
